import datetime
import random
import time
from util.myredis import r
from views.base import BaseHandler
import json
from db.datab import db
 # 出借
class Getlend(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        code = data['code']
        print(code)
        userid = data['userid']
        money = data['money']
        addtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        guser = "select * from user where id=%d" % (int(userid))
        user = db.findOne(guser)
        # 获取当前用户的金额
        pmoney = float(user['money'])

        umoney = int(pmoney) - int(money)
        print('++++++', umoney)
        # if re.findall('r^\d&')
        if int(money) > int(pmoney):
            return self.finish({'code':401,'msg':'金额不足'})

        number = hash(int(code))%3
        # print(number)
        tablename = 'landmarks'
        if number >0:
            tablename = tablename+str(number)
        # 查询需要借款人所有信息
        sql = "select * from "+tablename+" where code='%s'"%code
        res = db.findOne(sql)

        print(res)

        # 利息
        interest = float(res['interest_rate'])
        print('interest',interest)
        # 利息加还款金额
        tmoney = money + (money*int(interest))
        print(tmoney)

        # 状态
        status =1
        # 差多钱满标
        balance = int(float(res['money'])) - int(money)
        print('*****',balance)
        landmarksmoney = int(res['money'])
        if int(money) > int(landmarksmoney):
            return self.finish({'code': 402, 'msg': '超出当前用户所借金额'})
        sql1 = "insert into invest (userid, landmarksid, money, addtime, interest, tmoney, status) values (%d,%d,'%s','%s','%s','%s',%d)"%(int(userid), int(code), money, addtime, interest, tmoney, int(status))
        db.update(sql1)
        # 修改表还剩多少钱满标
        usql = "update "+tablename+" set money='%s' where code='%s'"%(balance,code)
        db.update(usql)

        # 锁定金额
        lockmoney = user['lockmoney']
        print(lockmoney)
        lmoney = int(lockmoney) + int(money)
        usql = "update user set money='%s',lockmoney='%s' where id=%d"%(umoney,lmoney,int(userid))
        db.update(usql)
        db.commit()
        times = time.time()
        r.sortedset_add('lendlandmarks',code,times)
        self.finish({'code':200,'msg':'出借成功'})


